import React, { useState , useRef, useEffect} from 'react'
import styles from './index.module.scss'
import { Card, Breadcrumb, Form, Input, Button, Space , Radio , Upload, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import { addArticle , editArticle } from '@/api/article'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import ArticleSelect from '@/components/ArticleSelect'
import { useSelector } from 'react-redux'
export default function Publish(props) {
  const [type, setType] = useState(1)
  const [fileList, setFileList] = useState([])
  const formRef = useRef(null)
  const id = props.match.params.id
  const data = useSelector(state=>state.publish)
  useEffect(() => {
    if (id && data) {
      // console.log(data.cover.type)
      formRef.current.setFieldsValue({ ...data,type:data.cover.type })
        setFileList(data.cover.images.map((img) => ({ url: img })))
        setType(data.cover.type)
    }  
  },[id,data])
  // setFieldsValue({属性名：属性值,...})
  // 上传图片列表
  // 图片张数
  // 保存 fileList 数据
  const countRef = useRef(fileList)
  // 获取图片列表数据
  const handleChange = ({fileList}) => {
    // console.log(file)
    setFileList(fileList)
    countRef.current = fileList
  }
  // 图片格式白名单
  const FILETYPE = ['image/jpg','image/gif', 'image/jpeg', 'image/png']
  // 格式校验
  const beforeUpload = (file) => {
    // console.log(file)
    !FILETYPE.includes(file.type)&&message.error('请传入正确格式')
  }
  // 获取选择的张数
  const typeChange = (e) => {
    if(!e)return
    setType(e.target.value)
    // console.log(type,e.target.value);
    setFileList(countRef.current.slice(0, e.target.value))
    formRef.current.validateFields(['imgs'])
  }
  // 表单数据处理
  const add = async (values,draf,id) => {
    // console.log(values)
    values = {
      title: values.title,
      content: values.content,
      channel_id: values.channel_id,
      cover: {
        type: values.type,
        images: fileList.map(it => it.response&&it.response.data.url)
      }
    }
    await id?editArticle(values, draf,id):addArticle(values, draf)
    props.history.push('/home/article')
  }
  // 发布or编辑
  const onFinish = (values) => {
    add(values,false ,id)
  } 
  // 存为草稿
  const addDraft = async () => {
    const res = await formRef.current.validateFields()
    console.log(res)
    add(res,true,id)
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{(id?'编辑':'发布')+'文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 
        表单数据收集: 
        - 给Form添加onFinish. `<Form onFinish={onFinish}`
        - 给Form.Item 添加name. `<Form.Item name="password">`
        - 给button的htmlType设为`submit` */}
        <Form ref={formRef} onFinish={onFinish} labelCol={{ span: 2 }} initialValues={{content:'',type}}  wrapperCol={{ span: 20 }} size="large">
          <Form.Item
            label="标题"
            name='title'
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name='channel_id'
            rules={[{ required: true, message: '请输入频道' }]}
          >
              <ArticleSelect></ArticleSelect>
          </Form.Item>
          <Form.Item
            label="封面"
            name='type'
            rules={[{ required: true, message: '请选择封面数量' }]}
          >
            <Radio.Group onChange={typeChange} value={type}>
              <Radio value={1}>一张</Radio>
              <Radio value={3}>三张</Radio>
              <Radio value={0}>不传</Radio>
            </Radio.Group>
          </Form.Item>
          {!!type && <Form.Item
            wrapperCol={{ offset: 2, span: 20 }}
            name='imgs'
            rules={[
              // { required: true, message: `请上传${type}张图片` },
              {
                validator() {
                  // console.log(type)
                if (fileList.length !== type) {
                  return Promise.reject(new Error(`请上传${type}张图片`))
                } else {
                  return Promise.resolve()
                }
              }}
            ]}
          >
            <Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={true}
              maxCount={type}
              fileList={fileList}
              action="http://geek.itheima.net/v1_0/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {fileList.length < type && <PlusOutlined></PlusOutlined>}
            </Upload>
          </Form.Item>}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
             <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 2, span: 20 }} name='btn'>
            <Space>
              <Button type="primary" htmlType='submit'>{(id?'编辑':'发布')+'文章'}</Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
